// -*- coding: utf-8 -*- 
/**
 * Project: AlgorithmsLearn
 *
 * @author: yanking
 * Create time: 2022-03-24 17:28
 * IDE: IntelliJ IDEA
 * Introduction:
 */
package com.LeetCodeT.DateTrain;

import org.junit.jupiter.api.Test;

public class ImageSmoother {
    /**
     * 图像平滑处理
     */
    public int[][] imageSmootherT(int[][] img) {
        /*-----设定图像运动的方向-----*/
        int[] x = {1, -1, 0, 0, -1, 1, 1, -1};
        int[] y = {0, 0, 1, -1, -1, 1, -1, 1};
        int[][] res = new int[img.length][img[0].length];
        /*-----遍历图像的像素点并且进行平滑操作-----*/
        for (int i = 0; i < img.length; i++) {
            for (int j = 0; j < img[0].length; j++) {
                int sum = img[i][j], n = 1;
                for (int k = 0; k < 8; k++) {
                    int newX = i + x[k];
                    int newY = j + y[k];
                    if (newX >= 0 && newX < img.length && newY >= 0 && newY < img[0].length) {
                        sum += img[newX][newY];
                        n++;
                    }
                }
                res[i][j] = sum / n;
            }
        }
        return res;
    }

    /**
     * 二维前缀和运用
     *
     * @param img
     * @return
     */
    public int[][] imageSmoother(int[][] img) {
        /*-----构造二维前缀和数组-----*/
        int n = img.length, m = n == 0 ? 0 : img[0].length;
        int[][] sum = new int[n + 1][m + 1];
        for (int i = 1; i < n; i++) {
            for (int j = 1; j < m; j++) {
                sum[i][j] = sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + img[i][j];
            }
        }
        /*-----根据前缀和数组平滑图片矩阵-----*/
        /*
            使用min&&max可以索引超出原矩阵
         */
        int[][] res = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                int a = Math.max(0, i - 1), b = Math.max(0, j - 1);
                int c = Math.min(n - 1, i + 1), d = Math.min(m, j + 1);
                int cnt = (c - a + 1) * (d - b + 1);
                res[i][j] = sum[c + 1][d + 1] - sum[a][d + 1] - sum[c + 1][b] + sum[a][b];
            }
        }
        return res;
    }


    @Test
    public void shout() {
        int[][] test = {{100, 200, 100}, {200, 50, 200}, {100, 200, 100}};
        test = imageSmoother(test);
        for (int[] ints : test) {
            for (int i = 0; i < ints.length; i++) {
                System.out.print(ints[i] + "\t");
            }
            System.out.println();
        }
    }
}
